package com.gzc.demo.validate;

import com.google.code.kaptcha.Producer;
import com.gzc.demo.config.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
@RequestMapping("/code")
public class ValidateCodeController {

	@Autowired
	Producer producer;
	@Autowired
	private RedisTemplate redisTemplate;

	@GetMapping("/image" + "/{randomStr}")
	public void createCode(@PathVariable String randomStr, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//Assert.isBlank(randomStr, "机器码不能为空");
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		//生成文字验证码
		String text = producer.createText();
		//生成图片验证码
		BufferedImage image = producer.createImage(text);
		//userService.saveImageCode(randomStr, text);

		redisTemplate.opsForValue().set(SecurityConstants.DEFAULT_CODE_KEY + randomStr, text, SecurityConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "JPEG", out);
		IOUtils.closeQuietly(out);
	}

	@ResponseBody
	@GetMapping("/sms" + "/{mobile}")
	public Response createSmsCode(@PathVariable String mobile, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//Assert.isBlank(randomStr, "机器码不能为空");
		response.setHeader("Cache-Control", "no-store, no-cache");
		//生成文字验证码
		String text = producer.createText();
		//生成图片验证码
		//userService.saveImageCode(randomStr, text);

		log.info("生成的手机验证码是" + text);
		redisTemplate.opsForValue().set(SecurityConstants.DEFAULT_CODE_KEY + mobile, text, SecurityConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);

		return new Response<>();
	}

}
